package com.dhsc.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName:  JsonUtil
 * @Description:json工具类
 * @author: wangxuebo
 * @date:   2018年9月12日 下午1:34:32       
 * @Copyright:  迅优智超
 */
public class JsonUtil
{
	private static final ObjectMapper mapper = new ObjectMapper();

	private JsonUtil()
	{

	}

	/**
	 * @Title: getObjectMapper   
	 * @Description: 获取ObjectMapper对象
	 * @author: wangxuebo
	 * @return      
	 * @return: ObjectMapper      
	 * @date:   2018年9月17日 下午9:27:14
	 */
	public static ObjectMapper getObjectMapper()
	{
		return mapper;
	}

	/**
	 * @Title: writeValueAsString   
	 * @Description:对象转json字符串
	 * @param: @param obj
	 * @param: @return String
	 * @param: @throws JsonProcessingException    
	 * @return: String      
	 * @throws:JsonProcessingException
	 */
	public static String writeValueAsString(Object obj) throws JsonProcessingException
	{
		if (null != obj)
		{
			return mapper.writeValueAsString(obj);
		}
		return "";
	}

	/**
	 * @Title: readValue   
	 * @Description:json字符串转对象
	 * @author: wangxuebo
	 * @param : jsonStr
	 * @param : c
	 * @return : <T> T
	 * @throws: IOException
	 * @date:   2018年9月9日 下午8:09:37
	 */
	public static <T> T readValue(String jsonStr, Class<T> c) throws IOException
	{
		if (null != jsonStr && !"".equals(jsonStr))
		{
			return mapper.readValue(jsonStr, c);
		}
		return null;
	}

	/**
	* @Description: json字符串转对象(忽略多余字段)
	* @MessageName: readValueIgnoreUnknown
	* @param: jsonStr
    * @param: c
	* @return: T
	* @Author: gx
	* @Date: 2025/4/8 11:26
	*/
	public static <T> T readValueIgnoreUnknown(String jsonStr, Class<T> c) throws IOException
	{
		if (null != jsonStr && !"".equals(jsonStr))
		{
			mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
			return mapper.readValue(jsonStr, c);
		}
		return null;
	}

	/**
	 * @Title: readValueAsList   
	 * @Description:json转list<bean>
	 * @author: wangxuebo
	 * @param jsonStr
	 * @param c
	 * @throws IOException      
	 * @return: List<T>      
	 * @date:   2018年9月16日 下午1:16:55
	 */
	public static <T> List<T> readValueAsList(String jsonStr,Class<T> c) throws IOException
	{
		if (null != jsonStr && !"".equals(jsonStr.trim()))
		{
			JavaType javaType = mapper.getTypeFactory().constructParametricType(List.class, c);
			return mapper.readValue(jsonStr, javaType);
		}
		return new ArrayList<>();
	}
	
	/**
	 * @Title: convertValue   
	 * @Description: object转相应对象
	 * @param obj
	 * @param c
	 * @return T
	 * @author: chenlin
	 * @date:   2020年5月26日 下午3:19:17
	 */
	public static <T> T convertValue(Object obj,Class<T> c){
		if (null != obj)
		{
			return mapper.convertValue(obj, c);
		}
		return null;
	}
	
}
